package com.zdp.usercenter.service.user;

import com.zdp.usercenter.dao.user.UserMapper;
import com.zdp.usercenter.domain.dto.user.UserLoginDTO;
import com.zdp.usercenter.domain.entity.user.User;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author sesshomaru
 * @date 2020/9/16 23:38
 */
@RequiredArgsConstructor(onConstructor = @_(@Autowired))
@Service
public class UserService {

    private final UserMapper userMapper;

    public User findById(Integer id) {
        // select * from user where id = #{id}
        return userMapper.selectByPrimaryKey(id);
    }

    public User login(UserLoginDTO loginDTO, String openId){
        User user = this.userMapper.selectOne(
                User.builder().wxId(openId).build()
        );

        if (user == null) {
            User userToSave = User.builder()
                    .wxId(openId)
                    .avatarUrl(loginDTO.getAvatarUrl())
                    .bonus(300)
                    .wxNickname(loginDTO.getWxNickName())
                    .roles("wxUser").createTime(new Date()).updateTime(new Date()).build();
            this.userMapper.insertSelective(
                    userToSave
            );
            return userToSave;
        }
        // 如果已经注册过 就直接返回user
        return user;
    }

}
